package com.zhj.juc.demo15;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.zhj.juc.demo15
 * @ClassName:Test1
 * @auter: 朱慧杰
 * @date:2020/7/25 0025 19:28
 **/
public class Test1 {

    // 可重入锁 拿到外边的锁 调用其他有锁的方法 也会拿到里边的锁 外边锁释放 其他线程才可以拿到里边的锁
    public static void main(String[] args) {

        Phone phone = new Phone();

        new Thread(()->{
            phone.sendSms();
        },"A").start();

        new Thread(()->{
            phone.sendSms();
        },"B").start();

    }

}

class Phone {

    Lock lock = new ReentrantLock();

    public void sendSms() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() +" 发短信");
            TimeUnit.SECONDS.sleep(2);
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() +" 打电话");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
